from cc_flask.models import db, String, Boolean, CModel, ForeignKey, ManyToMany


class UserGroup(CModel):
    name = String('分组名', default=True)

    default = ['name']  # 设置default字段，可通过 Group.get_default() 方法获取
    detail = ['id', 'name']  # 设置default字段，可通过 Group.get_detail() 方法获取

    def __repr__(self):
        return '<Group %r>' % self.name


class User(CModel):
    username = String('用户名称', unique=True)
    email = String('邮箱', unique=True)
    is_activity = Boolean('是否激活', default=False)
    phone = String('手机号', nullable=True)

    # ManyToMany 支持支持反向查询，如Group表反向查询User表：Group.query.first().user_set
    # 默认反向查询的字段为：正向表名 + _set，如：user_set、user_group_set
    group = ManyToMany(UserGroup, "user", comment='分组')

    detail = ['id', ("group", 'detail'), 'is_activity', 'username']
    default = ['id', 'is_activity', 'username']

    def __repr__(self):
        return '<User %r>' % self.username


class Article(CModel):
    title = String("标题", max_length=80)
    content = String("内容")

    # 显示的user_id是User表的id，user则是sqlalchemy中多对一两个表的关系字段
    # 这里默认支持反向查询，如User表反向查询Article：User.query.first().article_set
    # 反向查询的字段为：正向表名 + _set，如：article_set
    user_id, user = ForeignKey('User', 'article', to_table='user')
    tags = ManyToMany('Tags', table_name='article', comment='标签', to_table='tags')

    default = ['id', ("user", 'default')]
    detail = ['id', ("user", 'default')]

    def __repr__(self):
        return '<Article %r>' % self.title


class Tags(CModel):
    name = String("标签", max_length=20)
